/*global $Client*/
import React, { useState, useEffect, useCallback } from "react";
import CircularProgress from "@mui/material/CircularProgress";
import Box from "@mui/material/Box";
import ExcelJS from "exceljs"; // 导入 ExcelJS

// 报关单明细批量操作
const App = () => {
  const [loading, setLoading] = useState(true); // 初始状态为加载中

  const fetchData = useCallback(async () => {
    try {
      // 模拟等待 10 秒
      let pagedata = window.wdata;
      let detaildata = pagedata?.data?.Quotation_PDetails;
      let columnsDefinition = pagedata?.columnsDefinition;
      let fname = pagedata?.fname;
      console.log("detaildata", detaildata);

      // 去除真正意义的空行
      const filteredData = detaildata.filter((item) => {
        return !(
          item.AccountprtNo == null &&
          item.Englishname == null &&
          item.internalcode == null
        );
      });
      
      // 处理过滤后的数据
      console.log("filteredData", filteredData);

      // 这里可以添加其他处理逻辑
      // 创建 Excel 文件
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet(fname);

      // 添加表头
      worksheet.columns = columnsDefinition.map(col => ({
        header: col.header,
        key: col.key,
        width: col.width,
      }));


      // 添加数据行
      filteredData.forEach((item) => {
        const row = {};
        columnsDefinition.forEach((col) => {
          const keys = col.key.split(".");
          let value = item;
          keys.forEach((key) => {
            value = value?.[key];
          });
          row[col.key] = value;
        });
        worksheet.addRow(row);
      });

      // 导出为 Blob 并触发下载
      const buffer = await workbook.xlsx.writeBuffer();
      const blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });

      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      if(!fname){
        fname = "导出";
      }
      link.download = `${fname}.xlsx`;
      link.click();
    } catch (err) {
      console.error("Error fetching data:", err);
    } finally {
      setLoading(false);
      $Client.close();
    }
  }, []);

  useEffect(() => {
    const initialize = async () => {
      await window.zohoReadyPromise;
      console.log("ZOHO is ready", window.ZOHO);
      fetchData();
    };
    initialize();
  }, [fetchData]);
  return (
    <div>
      {loading && (
        <Box
          display="flex"
          justifyContent="center"
          alignItems="center"
          position="fixed"
          top={0}
          left={0}
          width="100%"
          height="100%"
          zIndex={9999} // 确保遮罩在最上层
          bgcolor="rgba(255, 255, 255, 0.8)" // 添加半透明背景
        >
          <CircularProgress />
        </Box>
      )}
    </div>
  );
};

export default App;
